package com.ghsc.ghxc.jsb.ui.my.fragment

import android.os.Bundle
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.load
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.setOnFastClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.transformRoundCorner
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.RefreshListBinding
import com.ghsc.ghxc.jsb.ext.showCustomPopup
import com.ghsc.ghxc.jsb.ui.my.activity.OrderDetailActivity
import com.ghsc.ghxc.jsb.ui.my.activity.OrderListViewModel
import com.ghsc.ghxc.jsb.ui.my.bean.OrderBean
import com.ghsc.ghxc.jsb.view.CenterSelectPopup
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my.fragment
 * 类名：OrderListFragment
 * 创建时间：2024/4/25 10:44
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class OrderListFragment : BaseVMFragment<OrderListViewModel, RefreshListBinding>(
    R.layout.refresh_list) {
    override fun attachVMClass(): Class<OrderListViewModel>? {
        return OrderListViewModel::class.java
    }

    override fun lazyLoad() {

    }
    var index: Int = 0

    companion object {
        fun getInstance(index: Int): OrderListFragment? {
            var fragment = OrderListFragment()
            fragment.index = index
            return fragment
        }
    }
    var isInit=false

    private val mAdapter by lazy { OrderListAdapter() }
    var mList = arrayListOf<OrderBean>()


    override fun initView(savedInstanceState: Bundle?) {
        binding.rvList.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvList.adapter = mAdapter
        mAdapter.replaceData(mList)
        mAdapter.setEmptyView(R.layout.layout_order_empty)
        mAdapter.addChildClickViewIds(R.id.stvCancel,R.id.stvpay,R.id.stvTuiKuan,R.id.stvSub)

        initRefreshLayout()
        pageNo = 1
        getListData()
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                if (rxBusBean.id == CustKey.REFRESH_ORDER && rxBusBean.sign == CustKey.REFRESH_ORDER) {
                    pageNo = 1
                    getListData()
                }else if (rxBusBean.id == CustKey.ORDER_TAB && rxBusBean.sign == CustKey.ORDER_TAB) {
                    var tabIndex =rxBusBean.anyBean as Int
                    if(tabIndex==index){
                        if (isInit){
                            binding.refreshLayout.autoRefresh()
                        }
                    }
                }
            }
    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    private fun getListData() {
        loge("请求订单接口="+index+"当前页"+pageNo)
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["otype"] = index
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.orderList(it1) }
    }

    override fun initClickListener() {
        super.initClickListener()
        mAdapter.setOnFastClickListener { data, position ->
            val bean = mAdapter.data[position]
            startKtxActivity<OrderDetailActivity>(
                values = arrayListOf(
                    "oid" to bean.oid,
                )
            )
        }

        mAdapter.setOnFastChildClickListener { view, position ->
            val bean = mAdapter.data[position]
            when (view.id) {
                R.id.stvCancel -> {
                    //取消订单
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                        .customHostLifecycle(lifecycle)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            ConfirmCancelPopViiew(requireActivity(),"提示","确定要取消该订单吗?",
                                btnConfirm={
                                    val map: HashMap<String, Any> = HashMap()
                                    map["oid"] = bean.oid
                                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.cancelOrder(it1) }
                                },
                                btnCancel={
                                },)
                        )
                        .show()
                }
                R.id.stvpay -> {
                    //去支付
                    startKtxActivity<OrderDetailActivity>(
                        values = arrayListOf(
                            "oid" to bean.oid,
                        )
                    )
                }
                R.id.stvTuiKuan -> {
                    //退款
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                        .customHostLifecycle(lifecycle)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            ConfirmCancelPopViiew(requireActivity(),"提示","确定要退款吗?",
                                btnConfirm={
                                    val map: HashMap<String, Any> = HashMap()
                                    map["oid"] = bean.oid
                                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShenqingTuikuan(it1) }
                                },
                                btnCancel={
                                },)
                        )
                        .show()
                }
                R.id.stvSub ->{
                    if(bean.status == "待发货"){
                        val map: HashMap<String, Any> = HashMap()
                        map["oid"] = bean.oid
                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onTixingFahuo(it1) }
                    }else if(bean.status == "待收货"){
                        //确认收货

                        XPopup.Builder(requireActivity())
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                            .customHostLifecycle(lifecycle)
                            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                            .asCustom(
                                ConfirmCancelPopViiew(requireActivity(),"提示","请您检查商品无误后再点击确认收货！确认收货后平台不支持退货退款哦",
                                    btnConfirm={
                                        val map: HashMap<String, Any> = HashMap()
                                        map["oid"] = bean.oid
                                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onQuerenShouhuo(it1) }
                                    },
                                    btnCancel={
                                    },)
                            )
                            .show()
                    }else{
                        //联系客服
                        showToast("暂未开放")
                    }
                }
            }
        }
    }
    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@OrderListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(it)
            }
            againLoginMsg.observe(this@OrderListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            orderListResult.observe(this@OrderListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.isNullOrEmpty()){
                        mAdapter.replaceData(it.data)
                        mAdapter.setEmptyView(R.layout.layout_order_empty)
                    }
                    else {
                        mAdapter.replaceData(it.data)
                    }
                } else {
                    if (!it.data.isNullOrEmpty())
                        mAdapter.addData(it.data)
                }
                isInit=true
            }

            cancelOrderResult.observe(this@OrderListFragment){
                showToast("订单已取消")
                binding.refreshLayout.autoRefresh()
            }
            onTixingFahuo.observe(this@OrderListFragment){
                showToast("已提醒发货")
            }
            //确认收货
            onQuerenShouhuo.observe(this@OrderListFragment){
                showToast("确认收货成功")
                binding.refreshLayout.autoRefresh()
            }
            onShenqingTuikuan.observe(this@OrderListFragment){
                showToast("申请成功")
                binding.refreshLayout.autoRefresh()
            }

        }
    }

    inner class OrderListAdapter : BaseQuickAdapter<OrderBean, BaseViewHolder>(R.layout.layout_order_item){


        override fun convert(holder: BaseViewHolder, item: OrderBean) {

            val ivOrderImg = holder.getView<ImageView>(R.id.ivOrderImg)
            ivOrderImg.load(item.skuimages, builder = {
                transform(transformRoundCorner(10))
            })

            holder.setText(R.id.tvOrderNumberHint,"订单编号:${item.oid}")
                .setText(R.id.tvOrderState,item.status)
                .setText(R.id.tvOrderName,item.title)
                .setText(R.id.tvPrice,item.price.toString()+"积分")
                .setText(R.id.tvOrderCount,item.cnt.toString())
                .setText(R.id.tvOrderCategory,item.skuvalue)
                .setText(R.id.tvTotalPriceDesc,"共 ${item.cnt} 件商品:  ")
                .setText(R.id.tvYunFei,item.yunfei.toString())
                .setText(R.id.tvState, if (item.status == "待支付") "需付款:" else "共付款:")
                .setText(R.id.tvPayRmb,item.pay_price.toString())


            if(item.status == "待支付" || item.status == "已失效"){
                holder.setText(R.id.stvCancel,"取消订单" )
                    .setGone(R.id.stvCancel,false)
            }else{
                holder.setGone(R.id.stvCancel,true)
            }

            if(item.status == "待支付"){
                holder.setText(R.id.stvpay,"去支付" )
                    .setGone(R.id.stvpay,false)
            }else{
                holder.setGone(R.id.stvpay,true)
            }

            if(item.status == "待发货"){
                holder.setText(R.id.stvTuiKuan,"退 款" )
                    .setGone(R.id.stvTuiKuan,false)
            }else{
                holder.setGone(R.id.stvTuiKuan,true)
            }

            if( item.status != "待支付" && item.status != "已失效"){
                holder.setText(R.id.stvSub,
                    if( item.status == "待发货") "提醒发货" else if( item.status == "待收货") "确认收货" else "联系客服")
                    .setGone(R.id.stvSub,false)
            }else{
                holder.setGone(R.id.stvSub,true)
            }


        }
    }
}